package com.googlecode.afdbaccess.config.webconfig;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import org.apache.log4j.Logger;

import com.googlecode.afdbaccess.cache.connectionpool.StandardDataSourcePool;
import com.googlecode.afdbaccess.cache.connectionpool.interfaces.ConnectionPool;
import com.googlecode.afdbaccess.cache.connectionpool.interfaces.ConnectionPoolFactory;
import com.googlecode.afdbaccess.cache.exceptions.DataLayerException;

public class AppServerPoolFactory implements ConnectionPoolFactory {
    private final static Logger log = Logger.getLogger(AppServerPoolFactory.class);
    
    /** Get a connection pool from the app server. */
    @Override
    public ConnectionPool getNewConnectionPool(String root) throws DataLayerException {
        if(root != null && root.equals("") == false) {
            if(root.endsWith("/") == false) {
                root += "/";
            }
        }
        
        final String lookupPath = "java:" + root + "Db";
        
        try {
            log.debug("Initializing context, Thread: " + Thread.currentThread());
            Context initCtx = new InitialContext();

            try {
                log.info("Trying to find datasource (" + lookupPath + "). Thread: " + Thread.currentThread());
                DataSource ds = (DataSource) initCtx.lookup(lookupPath);
    
                if(ds != null) {
                    log.info("Found datasource " + lookupPath + " (" + ds + "). Thread: " + Thread.currentThread());
                    return new StandardDataSourcePool(ds);
                } else {
                    throw new NamingException("Found null datasource. Check JDBC datasource configuration. " + lookupPath + " (" + ds + "). Thread: " + Thread.currentThread());
                }
            } catch (NamingException exception2) {
                throw new NamingException("Couldn't find datasource \"" + lookupPath + "\". Check JDBC datasource configuration.");
            }
        } catch(NamingException exception) {
            throw new DataLayerException("Couldn't lookup datasource: (" + lookupPath + ")", exception);
        } catch(Exception exception) {
            throw new DataLayerException("Couldn't create connection cache!", exception);
        }
    }

    @Override
    public ConnectionPool getNewConnectionPool() throws DataLayerException {
        return getNewConnectionPool("jdbc");
    }
}